<template>
  <div class="player" v-show="playlist.length > 0">
    <!--全屏播放-->
    <transition name="normal"
                @enter="enter"
                @after-enter="afterEnter"
                @leave="leave"
                @after-leave="afterLeave"
    >
      <div class="normal-player" v-show="fullScreen">
      <div class="background">
        <img  :src="currentSong.image" width="100%" height="100%" >
      </div>
      <div class="top">
        <div class="back" @click="back">
          <i class="icon-back"></i>
        </div>
        <h1 class="title" v-html="currentSong.name"></h1>
        <h2 class="subtitle" v-html="currentSong.singer"></h2>
      </div>
      <div class="middle"
           @touchstart.prevent="middleTouchStart"
           @touchmove.prevent="middleTouchMove"
           @touchend="middleTouchEnd">
        <div class="middle-l" ref="middleL">
          <div class="cd-wrapper" ref="cdWrapper">
            <div class="cd">
              <img class="image" :src="currentSong.image" :class="cdCls"/>
            </div>
            <div class="playing-lyric-wrapper">
              <div class="playing-lyric">{{playingLyric}}</div>
            </div>
          </div>
        </div>
        <scroll class="middle-r" ref="lyricList" :data="currentLyric && currentLyric.lines">
          <div class="lyric-wrapper">
            <div v-if="currentLyric">
              <p ref="lyricLine"
                 class="text"
                 :class="{'current':currentLineNum === index}"
                 v-for="(line,index) in currentLyric.lines">{{line.txt}}</p>
            </div>
          </div>
        </scroll>
      </div>
      <div class="bottom">
        <div class="dot-wrapper" >
          <span class="dot" :class="{'active': currentShow === 'cd'}"></span>
          <span class="dot" :class="{'active': currentShow === 'lyric'}"></span>
        </div>
        <div class="progress-wrapper">
          <span class="time time-l">{{format(currentTime)}}</span>
          <div class="progress-bar-wrapper">
            <progress-bar :precent="precent" @percentChange="onProgressBarChange"></progress-bar>
          </div>
          <span class="time time-r">{{format(currentSong.duration)}}</span>
        </div>
        <div class="operators">
          <div class="icon i-left" >
            <i :class="iconMode" @click="changeMode"></i>
          </div>
          <div class="icon i-left">
            <i @click="prev" class="icon-prev"></i>
          </div>
          <div class="icon i-center">
            <i @click="togglePlaying" :class="playIcon"></i>
          </div>
          <div class="icon i-right">
            <i @click="next" class="icon-next"></i>
          </div>
          <div class="icon i-right">
            <i class="icon" :class="getFavoriteIcon(currentSong)" @click="toggleFavorite(currentSong)"></i>
          </div>
        </div>
      </div>
    </div>
    </transition>
    <!--固定在屏幕底部的小播放器-->
    <transition name="mini">
      <div class="mini-player" v-show="!fullScreen" @click="open">
      <div class="icon">
        <img :src="currentSong.image" width="40" height="40" :class="cdCls"/>
      </div>
      <div class="text">
        <div class="name" v-html="currentSong.name"></div>
        <div class="desc" v-html="currentSong.singer"></div>
      </div>
      <div class="control">
        <progress-circle :radius="radius" :precent="precent" >
          <i @click.stop="togglePlaying" class="icon-mini" :class="miniIcon"></i>
        </progress-circle>
      </div>
      <div class="control" @click.stop="showPlayList">
        <i class="icon-playlist"></i>
      </div>
    </div>
    </transition>
    <playlist ref="playlist"></playlist>
    <audio :src="currentSong.url" ref="audio" @timeupdate="updateTime" @ended="ended" @canplay="ready" @error="error"></audio>
  </div>
</template>

<script type="text/ecmascript-6">
  import {mapGetters,mapMutations,mapActions} from 'vuex'
  import animations from 'create-keyframe-animation'
  import {prefixStyle} from "../../common/js/dom";
  import ProgressBar from "../../base/progress-bar/progress-bar";
  import ProgressCircle from "../../base/progress-circle/progress-circle";
  import {playMode} from "../../common/js/config";
  import Lyric from 'lyric-parser'
  import scroll from "../../base/scroll/scroll"
  import playlist from '../../components/playlist/playlist'
  import {playerMixin} from "../../common/js/mixin";
  import {getLyric} from "../../api/song";

  let _this = null;

  const transform = prefixStyle('transform')
  //过渡时间持续
  const transitionDuration = prefixStyle('transitionDuration')

  export default {
    mixins:[playerMixin],
    props: [],
    data(){
      return {
        songReady:false,
        currentTime:0,
        radius:32,
        currentLyric:null,
        currentLineNum:0,
        currentShow:'cd',
        playingLyric:'',
        songurl:''
      }
    },
    mounted () {
      _this = this;
      _this.init();
    },
    created(){
     this.touch = {}
    },
    methods: {
      init () {

      },
      //播放结束
      ended(){
        //单曲循环
        if(this.mode === playMode.loop){
          this._loop()
        }else{
          this.next()
        }
      },
      //单曲循环
      _loop(){
        this.$refs.audio.currentTime = 0
        this.$refs.sudio.play()
        //循环播放时歌曲到最后从头开始时歌词也重新开始
        if(this.currentLyric){
          this.currentLyric.seek(0)
        }
      },
      back(){
        this.setFullScreen(false)
      },
      open(){
        this.setFullScreen(true)
      },
      //播放  /  暂停
      togglePlaying(){
        this.setPlayingState(!this.playing)
        //停止播放时歌词也停止
        if(this.songReady){
          this.currentLyric.togglePlay()
        }
      },
      prev(){
        if(this.playlist.length === 1){
          this._loop()
          return
        }else {
          let index = this.currentIndex - 1;
          if (index === -1) {
            index = this.playlist.length - 1
          }
          this.setCurrentIndex(index)
          if (!this.playing) {
            this.togglePlaying()
          }
        }
      },
      next(){
        if(this.playlist.length === 1){
          this._loop()
          return
        }else {
          let index = this.currentIndex + 1;
          if (index === this.playlist.length) {
            index = 0
          }
          this.setCurrentIndex(index)
          //暂停的时候点到下首歌时会自动播放，需要加个逻辑改变playing的状态
          if (!this.playing) {
            this.togglePlaying()
          }
        }
      },
      ready() {
        this.songReady = true
        this.savePlayHistory(this.currentSong)
      },
      error() {
        this.songReady = true
      },
      //当前播放的时间
      updateTime(e){
        this.currentTime = e.target.currentTime
      },
      //将时间转化为正常的
      format(time){
        //向下取整
        time = time | 0
        let minute = time / 60 | 0
        let second = this._pad(time % 60)
        return `${minute}:${second}`
      },
      _pad(num,n=2){
        let len = num.toString().length
        while(len<n){
          num = '0'+num
          len++
        }
        return num
      },
      onProgressBarChange(percent){
        //当前播放的时间
        const currentTime = this.currentSong.duration * percent
        // console.log(currentTime*1000)
        this.$refs.audio.currentTime = currentTime
        //
        if (!this.playing) {
          this.togglePlaying()
        }
        //进度条拖动歌词一起变动
        if(this.currentLyric){
          //
          this.currentLyric.seek(currentTime * 1000)
        }
      },
      showPlayList(){
        this.$refs.playlist.show()
      },
      enter(el,done){
        const {x,y,scale} = this._getPosAndScale(this.$refs.cdWrapper,'move',done)
        let animation = {
          0:{
            transform:`translate3d(${x}px,${y}px,0) scale(${scale})`
          },
          60:{
            transform:`translate3d(0,0,0) scale(1.1)`
          },
          100:{
            transform:`translate3d(0,0,0) scale(1)`
          }
        }
        animations.registerAnimation({
          name:'move',
          animation,
          presets:{
            duration:400,
            easing:'linear'
          }
        })
        animations.runAnimation(this.$refs.cdWrapper,'move',done)
      },
      afterEnter(){
        //将动画animation清除
        animations.unregisterAnimation('move')
        this.$refs.cdWrapper.style.animation = ''
      },
      leave(el,done){
        //不需要animation  用transition就可以设置了
        this.$refs.cdWrapper.style.transition = 'all 0.4s'
        const {x, y, scale} = this._getPosAndScale()
        this.$refs.cdWrapper.style[transform] = `translate3d(${x}px,${y}px,0) scale(${scale})`
        this.$refs.cdWrapper.addEventListener('transitionend', done)
      },
      afterLeave(){
        //清除动画和缩放
        this.$refs.cdWrapper.style.transition = ''
        this.$refs.cdWrapper.style[transform] = ''
      },
      //得到图片从小屏动画到大屏的初始值
      _getPosAndScale(){
        //小屏图片的宽度
        const targetWidth = 40
        //小屏图片距左边的距离
        const paddingLeft = 40
        const paddingBottom = 30
        //大屏图片和上边的距离
        const paddingTop = 80
        //大屏图片的宽度
        const width = window.innerWidth * 0.8
        //一开始的缩放
        const scale = targetWidth / width
        //从小屏图片到大屏图片的距离x和y
        const x = -(window.innerWidth / 2 - paddingLeft)
        const y = window.innerHeight - paddingTop - width / 2 - paddingBottom
        return {
          x,
          y,
          scale
        }
      },
      _getLyric(){
        // getLyric().then((lyric) => {
        //   //不是当前这首歌的歌词就返回
        //   // if(this.currentSong.lyric !== lyric){
        //   //   return
        //   // }
        //   //this.handleLyric是lyric一个方法
        //   console.log(lyric)
        //   this.currentLyric = new Lyric(lyric, this.handleLyric)
        //   console.log(this.currentLyric)
        //   if(this.playing) {
        //     this.currentLyric.play()
        //   }
        //   // console.log(this.currentLyric)
        // }).catch(()=>{
        //   this.currentLyric = null
        //   this.playingLyric = ''
        //   this.currentLineNum = 0
        // })
        let index = Base64.decode(this.lyric.lyric)
        console.log(index)
        // console.log(index)
        this.currentLyric = new Lyric(index, this.handleLyric)
        console.log(this.currentLyric)
        if(this.playing) {
          this.currentLyric.play()
        }

      },
      handleLyric({lineNum,txt}){
        this.currentLineNum = lineNum
        if(lineNum>5){
          let line = this.$refs.lyricLine[lineNum - 5]
          this.$refs.lyricList.scrollToElement(line, 1000)
        }else{
          this.$refs.lyricList.scrollTo(0.0,1000)
        }
        this.playingLyric = txt
      },
      middleTouchStart(e) {
        this.touch.initiated = true
        // 用来判断是否是一次移动
        this.touch.moved = false
        const touch = e.touches[0]
        this.touch.startX = touch.pageX
        this.touch.startY = touch.pageY
      },
      middleTouchMove(e) {
        if (!this.touch.initiated) {
          return
        }
        const touch = e.touches[0]
        const deltaX = touch.pageX - this.touch.startX
        const deltaY = touch.pageY - this.touch.startY

        if (Math.abs(deltaY) > Math.abs(deltaX)) {
          return
        }
        if (!this.touch.moved) {
          this.touch.moved = true
        }
        //判断lyric是在最左边(就是当前屏幕的宽度)还是最右边(值就为0)
        const left = this.currentShow === 'cd' ? 0 : -window.innerWidth
        //计算歌词的位置（Math.max  最大的位置就是歌词到最右边 detailX+left 歌词会随着手指的滑动往左边移动）值都是负的
        const offsetWidth = Math.min(0, Math.max(-window.innerWidth, left + deltaX))
        this.touch.percent = Math.abs(offsetWidth / window.innerWidth)
        //lyricList  现在在scroll上面，是vue组件 必须用$el
        this.$refs.lyricList.$el.style[transform] = `translate3d(${offsetWidth}px,0,0)`
        //歌词列表过渡时间
        this.$refs.lyricList.$el.style[transitionDuration] = 0
        this.$refs.middleL.style.opacity = 1 - this.touch.percent

        this.$refs.middleL.style[transitionDuration] = 0
      },

      middleTouchEnd() {
        if (!this.touch.moved) {
          return
        }
        let offsetWidth
        let opacity
        if (this.currentShow === 'cd') {
          //从右向左滑的时候大于屏幕的10%时就可以自动划过去
          if (this.touch.percent > 0.1) {
            offsetWidth = -window.innerWidth
            opacity = 0
            this.currentShow = 'lyric'
          } else {
            offsetWidth = 0
            opacity = 1
          }
        } else {
          if (this.touch.percent < 0.9) {
            offsetWidth = 0
            this.currentShow = 'cd'
            opacity = 1
          } else {
            offsetWidth = -window.innerWidth
            opacity = 0
          }
        }
        const time = 300
        this.$refs.lyricList.$el.style[transform] = `translate3d(${offsetWidth}px,0,0)`
        this.$refs.lyricList.$el.style[transitionDuration] = `${time}ms`
        this.$refs.middleL.style.opacity = opacity
        this.$refs.middleL.style[transitionDuration] = `${time}ms`
        this.touch.initiated = false
      },
      ...mapMutations({
        setFullScreen: 'SET_FULL_SCREEN',
      }),
        ...mapActions([
          'savePlayHistory'
        ])
    },
    watch: {
      currentSong(newSong,oldSong){
        //播放列表没有歌曲时会报this.currentLyric的错，是因为修改了currentIndex和playList导致了currentSong发生变化
        if(!newSong.id){
          return
        }
        if(newSong.id === oldSong.id){
          return;
        }
        //切换下一首歌时现将之前创建的关闭掉
        if(this.currentLyric){
          this.currentLyric.stop()
        }
        this.$nextTick(()=>{
          this.$refs.audio.play()
          //当前歌单的歌词
          // this.currentSong.getLyric()
          this._getLyric()
        },20)
      },
      playing(newPlaying){
        this.$nextTick(() => {
          const audio = this.$refs.audio
          // newPlaying ? audio.play():audio.pause()
          if(newPlaying){
            setTimeout(() => {
              audio.play()
            },150)
          }else{
            setTimeout(() => {
              audio.pause()
            },150)
          }
        })
      }
    },
    components: {scroll, ProgressCircle, ProgressBar,playlist},
    computed: {
      ...mapGetters([
        'fullScreen',
        'playing',
        'currentIndex',
        'lyric'
      ]),
      playIcon(){
        return this.playing ?'icon-pause' : 'icon-play'
      },
      miniIcon(){
        return this.playing ?'icon-pause-mini' : 'icon-play-mini'
      },
      cdCls() {
        return this.playing ? 'play' : 'play pause'
      },
      //播放的比列
      precent(){
        return this.currentTime / this.currentSong.duration
      },
    },

  }
</script>


<style lang="stylus" rel="stylesheet/stylus">
  @import '../../common/stylus/variable.styl';
  @import "../../common/stylus/mixin.styl"

  .player
    .normal-player
      position: fixed
      left: 0
      right: 0
      top: 0
      bottom: 0
      z-index: 150
      background: $color-background
      .background
        position: absolute
        left: 0
        top: 0
        width: 100%
        height: 100%
        z-index: -1
        opacity: 0.6
        filter: blur(20px)
      .top
        position: relative
        margin-bottom: 25px
        .back
          position absolute
          top: 0
          left: 6px
          z-index: 50
          .icon-back
            display: block
            padding: 9px
            font-size: $font-size-large-x
            color: $color-theme
            transform: rotate(-90deg)
        .title
          width: 70%
          margin: 0 auto
          line-height: 40px
          text-align: center
          no-wrap()
          font-size: $font-size-large
          color: $color-text
        .subtitle
          line-height: 20px
          text-align: center
          font-size: $font-size-medium
          color: $color-text
      .middle
        position: fixed
        width: 100%
        top: 80px
        bottom: 170px
        white-space: nowrap
        font-size: 0
        .middle-l
          display: inline-block
          vertical-align: top
          position: relative
          width: 100%
          height: 0
          padding-top: 80%
          .cd-wrapper
            position: absolute
            left: 10%
            top: 0
            width: 80%
            height: 100%
            .cd
              width: 100%
              height: 100%
              box-sizing: border-box
              border: 10px solid rgba(255, 255, 255, 0.1)
              border-radius: 50%
              .image
                position: absolute
                left: 0
                top: 0
                width: 100%
                height: 100%
                border-radius: 50%
                &.play
                  animation: rotate 20s linear infinite
                &.pause
                  animation-play-state: paused

          .playing-lyric-wrapper
            width: 80%
            margin: 30px auto 0 auto
            overflow: hidden
            text-align: center
            .playing-lyric
              height: 20px
              line-height: 20px
              font-size: $font-size-medium
              color: $color-text-l
        .middle-r
          display: inline-block
          vertical-align: top
          width: 100%
          height: 100%
          overflow: hidden
          .lyric-wrapper
            width: 80%
            margin: 0 auto
            overflow: hidden
            text-align: center
            .text
              line-height: 32px
              color: $color-text-l
              font-size: $font-size-medium
              &.current
                color: $color-text
      .bottom
        position: absolute
        bottom: 50px
        width: 100%
        .dot-wrapper
          text-align: center
          font-size: 0
          .dot
            display: inline-block
            vertical-align: middle
            margin: 0 4px
            width: 8px
            height: 8px
            border-radius: 50%
            background: $color-text-l
            &.active
              width: 20px
              border-radius: 5px
              background: $color-text-ll
        .progress-wrapper
          display: flex
          align-items: center
          width: 80%
          margin: 0px auto
          padding: 10px 0
          .time
            color: $color-text
            font-size: $font-size-small
            flex: 0 0 30px
            line-height: 30px
            width: 30px
            &.time-l
              text-align: left
            &.time-r
              text-align: right
          .progress-bar-wrapper
            flex: 1
        .operators
          display: flex
          align-items: center
          .icon
            flex: 1
            color: $color-theme
            &.disable
              color: $color-theme-d
            i
              font-size: 30px
          .i-left
            text-align: right
          .i-center
            padding: 0 20px
            text-align: center
            i
              font-size: 40px
          .i-right
            text-align: left
          .icon-favorite
            color: $color-sub-theme
      &.normal-enter-active, &.normal-leave-active
        transition: all 0.4s
        .top, .bottom
          transition: all 0.4s cubic-bezier(0.86, 0.18, 0.82, 1.32)
      &.normal-enter, &.normal-leave-to
        opacity: 0
        .top
          transform: translate3d(0, -100px, 0)
        .bottom
          transform: translate3d(0, 100px, 0)
    .mini-player
      display: flex
      align-items: center
      position: fixed
      left: 0
      bottom: 0
      z-index: 180
      width: 100%
      height: 60px
      background: $color-highlight-background
      &.mini-enter-active, &.mini-leave-active
        transition: all 0.4s
      &.mini-enter, &.mini-leave-to
        opacity: 0
      .icon
        flex: 0 0 40px
        width: 40px
        padding: 0 10px 0 20px
        img
          border-radius: 50%
          &.play
            animation: rotate 10s linear infinite
          &.pause
            animation-play-state: paused
      .text
        display: flex
        flex-direction: column
        justify-content: center
        flex: 1
        line-height: 20px
        overflow: hidden
        .name
          margin-bottom: 2px
          no-wrap()
          font-size: $font-size-medium
          color: $color-text
        .desc
          no-wrap()
          font-size: $font-size-small
          color: $color-text-d
      .control
        flex: 0 0 30px
        width: 30px
        padding: 0 10px
        .icon-play-mini, .icon-pause-mini, .icon-playlist
          font-size: 30px
          color: $color-theme-d
        .icon-mini
          font-size: 32px
          position: absolute
          left: 0
          top: 0

  @keyframes rotate
    0%
      transform: rotate(0)
    100%
      transform: rotate(360deg)
</style>
